import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { Message } from 'element-ui'
import { getTimeStamp } from '@/utils/auth.js'
const TimeOut = 3600
// create an axios instance 创建实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

// request interceptor 请求拦截器
service.interceptors.request.use(config => {
  if (store.getters.token) {
    if (isUpToDate()) {
      store.dispatch('user/logout')
      router.push('/login')
      return Promise.reject(new Error('token过期'))
    }
    config.headers['Authorization'] = 'Bearer ' + store.getters.token
  }
  return config
}, error => {
  return new Promise(error)
})

// response interceptor 响应拦截器
service.interceptors.response.use(response => {
  const { message, data, success } = response.data
  if (success) {
    return data
  } else {
    Message.error(message)
    return Promise.reject(new Error(message))
  }
}, error => {
  // if(error.response&& error.response.status===404){
  // }
  if (error.response && error.response.data && error.response.data.code === 10002) {
    store.dispatch('user/logout')
    router.push('/login')
  } else {
    Message.error(error.message)
  }

  return Promise.reject(error)
})

function isUpToDate() {
  const currentTime = Date.now()
  const timeStamp = getTimeStamp()
  return (currentTime - timeStamp) / 1000 > TimeOut
}

export default service
